import CustomRender from "./CustomRenderV2";

const gfx = cc['gfx'];

let vfmtPosUvColorFront = new gfx.VertexFormat([
    // 节点的世界坐标，占2个float32
    { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },

    // 节点的纹理uv坐标，占2个float32
    // 如果节点使用了独立的纹理（未合图），这里的uv值通常是0或1
    // 合图后的纹理，这里的uv对应其在图集里的相对位置，取值范围在[0,1)内
    { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },

    // 节点颜色值，占4个uint8 = 1个float32
    { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true },
]);

export default class CustomAssemblerV2 extends cc.Assembler {
    // 普通四边形的属性，根据实际的顶点格式、数量调整

    /** 四边形顶点数量 = 4 */
    protected verticesCount = 4;

    /** 一个四边形按照对角拆分成2个三角形，2*3 = 6个顶点索引 */
    protected indicesCount = 6;

    /** vfmtPosUvColor 结构占5个float32 */
    protected floatsPerVert = 5;

    /** vdata offset info (default = 2) */
    protected uvOffset = 2;

    /** 颜色取值偏移 (default = 4) */
    protected colorOffset = 4;

    protected _renderData: cc.RenderData = null;
    protected _local = null;

    public updateRenderData(comp: cc.RenderComponent) {
        if (comp._vertsDirty) {
            this.updateUVs(comp);
            this.updateVerts(comp);
            comp._vertsDirty = false;
        }
    }

    /**
     * @override
     * @dec 初始化 `_renderData` 数据
     */
    init(comp: cc.RenderComponent) {
        super.init(comp);

        this._renderData = new cc.RenderData();
        this._renderData.init(this);

        this.initData();
        this.initLocal();
    }

    /** 当前节点的所有顶点数据总大小 */
    get verticesFloats() {
        return this.verticesCount * this.floatsPerVert;
    }

    initData() {
        // // this.renderData = new cc.RenderData();
        // // this.renderData.init(this);

        // let data = this.renderData;
        // // createFlexData 支持创建指定格式的 renderData
        // data.createFlexData(0, this.verticesCount, this.indicesCount, this.getVfmt());

        // // createFlexData 不会填充顶点索引信息
        // // 顶点数固定的情况下索引不变化
        // let indices = data.iDatas[0];
        // this.initQuadIndices(indices);

        let data = this._renderData;
        data.createQuadData(0, this.verticesFloats, this.indicesCount);
    }

    initLocal() {
        this._local = [];
        this._local.length = 4;
    }

    /** 更新颜色 */
    updateColor(comp: any, color: any) {
        let uintVerts = this._renderData.uintVDatas[0];
        if (!uintVerts) return;
        color = color != null ? color : comp.node.color._val;
        let floatsPerVert = this.floatsPerVert;
        let colorOffset = this.colorOffset;
        for (let i = colorOffset, l = uintVerts.length; i < l; i += floatsPerVert) {
            uintVerts[i] = color;
        }
    }

    /**
     * 重载getBuffer(), 默认fillBuffers()方法中会调用到
     * @returns 返回一个能容纳自定义顶点数据的buffer
     */
    getBuffer() {
        //@ts-ignore
        return cc.renderer._handle.getBuffer("mesh", this.getVfmt());
    }

    getVfmt() {
        return vfmtPosUvColorFront;
    }

    updateWorldVerts(comp: any) {
        let local = this._local;
        let verts = this._renderData.vDatas[0];

        let matrix = comp.node._worldMatrix;
        let matrixm = matrix.m;
        // matrixm 单位矩阵
        // [1, 0, 0, 0
        //  0, 1, 0, 0
        //  0, 0, 1, 0
        //  0, 0, 0, 1]
        let a = matrixm[0];
        let b = matrixm[1];
        let c = matrixm[4];
        let d = matrixm[5];
        let tx = matrixm[12];
        let ty = matrixm[13];

        let vl = local[0];
        let vr = local[2];
        let vb = local[1];
        let vt = local[3];

        let justTranslate = a === 1 && b === 0 && c === 0 && d === 1;

        let index = 0;
        let floatsPerVert = this.floatsPerVert;
        if (justTranslate) {
            // left bottom
            verts[index] = vl + tx;
            verts[index + 1] = vb + ty;
            index += floatsPerVert;

            // right bottom
            verts[index] = vr + tx;
            verts[index + 1] = vb + ty;
            index += floatsPerVert;

            // left top
            verts[index] = vl + tx;
            verts[index + 1] = vt + ty;
            index += floatsPerVert;

            // right top
            verts[index] = vr + tx;
            verts[index + 1] = vt + ty;
        } else {
            let al = a * vl;
            let ar = a * vr;
            let bl = b * vl;
            let br = b * vr;
            let cb = c * vb;
            let ct = c * vt;
            let db = d * vb;
            let dt = d * vt;

            // left bottom
            verts[index] = al + cb + tx;
            verts[index + 1] = bl + db + ty;
            index += floatsPerVert;

            // right bottom
            verts[index] = ar + cb + tx;
            verts[index + 1] = br + db + ty;
            index += floatsPerVert;

            // left top
            verts[index] = al + ct + tx;
            verts[index + 1] = bl + dt + ty;
            index += floatsPerVert;

            // right top
            verts[index] = ar + ct + tx;
            verts[index + 1] = br + dt + ty;
        }
    }

    updateVerts(comp: cc.RenderComponent) {
        let node = comp.node;
        let cw = node.width;
        let ch = node.height;
        let appx = node.anchorX * cw;
        let appy = node.anchorY * ch;
        let l: number;
        let b: number;
        let r: number;
        let t: number;

        l = - appx;
        b = - appy;
        r = cw - appx;
        t = ch - appy;

        let local = this._local;
        local[0] = l;
        local[1] = b;
        local[2] = r;
        local[3] = t;
        this.updateWorldVerts(comp);
    }

    updateUVs(sprite: any) {
        // console.log(sprite);
        // UV 的纹理坐标在左上角
        // 顶点索引从左下角开始
        let uv = [0, 1, 1, 1, 0, 0, 1, 0];
        // let uv = [0, 0, 1, 0, 0, 1, 1, 1];

        /** vdata offset info (default = 2) */
        let uvOffset = this.uvOffset;
        
        /** vfmtPosUvColor 结构占5个float32 */
        let floatsPerVert = this.floatsPerVert;

        /** 
         * @dec renderData.vDatas 用来存储 pos, uv, color 数据 
         * @dec pos.x, pos.y, uv.x, uv.y, color
        */
        let verts = this._renderData.vDatas[0];

        for (let i = 0; i < 4; i++) {
            let srcOffset = i * 2;
            let dstOffset = floatsPerVert * i + uvOffset;
            verts[dstOffset] = uv[srcOffset];
            verts[dstOffset + 1] = uv[srcOffset + 1];
        }
    }

    /** init quad indices (初始化四边形顶点索引) */
    initQuadIndices(indices: any[]) {
        let count = indices.length / 6;
        for (let i = 0, idx = 0; i < count; i++) {
            let vertextID = i * 4;
            indices[idx++] = vertextID;
            indices[idx++] = vertextID + 1;
            indices[idx++] = vertextID + 2;
            indices[idx++] = vertextID + 1;
            indices[idx++] = vertextID + 3;
            indices[idx++] = vertextID + 2;
        }
    }

    fillBuffers(comp, renderer) {
        let renderData = this._renderData;
        let vData = renderData.vDatas[0];
        let iData = renderData.iDatas[0];

        let buffer = this.getBuffer();
        let offsetInfo = buffer.request(this.verticesCount, this.indicesCount);

        let vertexOffset = offsetInfo.byteOffset >> 2,
            vbuf = buffer._vData;

        if (vData.length + vertexOffset > vbuf.length) {
            vbuf.set(vData.subarray(0, vbuf.length - vertexOffset), vertexOffset);
        } else {
            vbuf.set(vData, vertexOffset);
        }

        let ibuf = buffer._iData,
            indiceOffset = offsetInfo.indiceOffset,
            vertexId = offsetInfo.vertexOffset;
        for (let i = 0, l = iData.length; i < l; i++) {
            ibuf[indiceOffset++] = vertexId + iData[i];
        }
    }
}
